
package com.kevin;


import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.util.*;


public class CodeGeneratorUtil {


    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("generator/entity.java.vm");
        templates.add("generator/entityDto.java.vm");
//        templates.add("generator/Dao.java.vm");
        templates.add("generator/Mapper.java.vm");
        templates.add("generator/Mapper.xml.vm");
        templates.add("generator/Service.java.vm");
        templates.add("generator/ServiceImpl.java.vm");
        templates.add("generator/Controller.java.vm");
        templates.add("generator/entitySelectParamsDto.java.vm");
        //templates.add("generator/list.html.vm");
        //templates.add("generator/add.html.vm");
        //templates.add("generator/edit.html.vm");
        //templates.add("generator/list.js.vm");
        //templates.add("generator/add.js.vm");
        //templates.add("generator/edit.js.vm");
        ////templates.add("generatormenu.sql.vm");
        return templates;
    }

    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns,String packagePath) throws IOException {
        //配置信息
        Configuration config = ContextUtil.getConfig("application.properties");
        //表信息
        TableInfo tableInfo = new TableInfo();
        tableInfo.setTableName(table.get("tableName"));
        tableInfo.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableInfo.getTableName(), config.getString("tablePrefix"), config.getString("autoRemovePre"));
        tableInfo.setClassName(className);
        tableInfo.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnInfo> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnInfo columnDO = new ColumnInfo();
            columnDO.setColumnName(column.get("columnName"));
            columnDO.setDataType(column.get("dataType"));
            columnDO.setComments(column.get("columnComment"));
            columnDO.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnDO.getColumnName());
            columnDO.setAttrName(attrName);
            columnDO.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnDO.getDataType(), "unknowType");
            columnDO.setAttrType(attrType);

            //列的数据类型，转换成jdbc类型 用于mapper的生成
            String jdbcType = config.getString(columnDO.getDataType()+"jdbc", "unknowType");
            columnDO.setJdbcType(jdbcType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableInfo.getPk() == null) {
                tableInfo.setPk(columnDO);
            }

            columsList.add(columnDO);
        }
        tableInfo.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableInfo.getPk() == null) {
            tableInfo.setPk(tableInfo.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", tableInfo.getTableName());
        map.put("controllerUrl", StringUtils.replace(tableInfo.getTableName(),"_","-"));
        map.put("comments", tableInfo.getComments());
        map.put("pk", tableInfo.getPk());
        map.put("className", tableInfo.getClassName());
        map.put("classname", tableInfo.getClassname());
        map.put("pathName", config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1));
        map.put("columns", tableInfo.getColumns());
        map.put("package", config.getString("package"));
        map.put("folder",config.getString("folder"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtil.format(new Date(), DateUtil.DATE_PATTERN));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            String filename = getFileName(template, tableInfo.getClassname(), tableInfo.getClassName(), packagePath);

            File file = new File(filename);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }

            OutputStream os = new FileOutputStream(file);

            IOUtils.write(sw.toString(), os, "UTF-8");
            IOUtils.closeQuietly(sw);
            os.close();
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix, String autoRemovePre) {
        if (Constants.AUTO_REOMVE_PRE.equals(autoRemovePre)) {
            tableName = tableName.substring(tableName.indexOf("_") + 1);
        }
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }

        return columnToJava(tableName);
    }


    /**
     * 获取文件名
     */
    public static String getFileName(String template, String classname, String className, String packageName) throws IOException {
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        String packagePath = courseFile + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
        //String modulesname=config.getString("packageName");
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }

        if (template.contains("entity.java.vm")) {
            return packagePath + className + ".java";
        }

        if (template.contains("entityDto.java.vm")) {
            return packagePath + className + "Dto.java";
        }
//        if (template.contains("Dao.java.vm")) {
//            return packagePath + className + "Dao.java";
//        }

		if(template.contains("Mapper.java.vm")){
			return packagePath + className + "Mapper.java";
		}

        if (template.contains("Service.java.vm")) {
            return packagePath + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm")) {
            return packagePath + className + "Controller.java";
        }

        if (template.contains("entitySelectParamsDto.java.vm")) {
            return packagePath + className + "SelectParamsDto.java";
        }

        if (template.contains("Mapper.xml.vm")) {
            return packagePath + className + "Mapper.xml";
            //return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + packageName + File.separator + className + "Mapper.xml";
        }
        //
        //if (template.contains("list.html.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
        //            + packageName + File.separator + classname + File.separator + classname + ".html";
        //    //				+ "modules" + File.separator + "generator" + File.separator + className.toLowerCase() + ".html";
        //}
        //if (template.contains("add.html.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
        //            + packageName + File.separator + classname + File.separator + "add.html";
        //}
        //if (template.contains("edit.html.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
        //            + packageName + File.separator + classname + File.separator + "edit.html";
        //}
        //
        //if (template.contains("list.js.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
        //            + "appjs" + File.separator + packageName + File.separator + classname + File.separator + classname + ".js";
        //    //		+ "modules" + File.separator + "generator" + File.separator + className.toLowerCase() + ".js";
        //}
        //if (template.contains("add.js.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
        //            + "appjs" + File.separator + packageName + File.separator + classname + File.separator + "add.js";
        //}
        //if (template.contains("edit.js.vm")) {
        //    return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
        //            + "appjs" + File.separator + packageName + File.separator + classname + File.separator + "edit.js";
        //}
        //

        return null;
    }
}
